package cn.zhentao.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DatabaseConfig {
    
    // 移除@Value注解，完全硬编码MySQL配置

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        // 使用远程MySQL配置
        config.setJdbcUrl("jdbc:mysql://8.136.2.98:3306/tutor?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&createDatabaseIfNotExist=true");
        config.setUsername("root");
        config.setPassword("banbanAiMysql");
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        // Hikari连接池配置 - 增加网络容错
        config.setMaximumPoolSize(20);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(60000);  // 增加到60秒
        config.setIdleTimeout(600000);
        config.setMaxLifetime(1800000);
        config.setLeakDetectionThreshold(60000);
        config.setValidationTimeout(5000);
        
        // MySQL特定配置 - 增加网络容错
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("autoReconnect", "true");
        config.addDataSourceProperty("failOverReadOnly", "false");
        config.addDataSourceProperty("maxReconnects", "3");
        config.addDataSourceProperty("initialTimeout", "2");
        config.addDataSourceProperty("connectTimeout", "60000");
        config.addDataSourceProperty("socketTimeout", "60000");
        
        System.out.println("✅ 创建MySQL数据源: jdbc:mysql://8.136.2.98:3306/tutor");
        System.out.println("✅ 驱动类: com.mysql.cj.jdbc.Driver");
        System.out.println("✅ 用户名: root");
        return new HikariDataSource(config);
    }
} 